/**
* \brief 
* \author pengcheng (pengcheng@yslrpch@126.com)
* \date 2020-05-30
* \attention CopyrightÃ‚Â©ADC Technology(tianjin)Co.Ltd
* \attention Refer to COPYRIGHT.txt for complete terms of copyright notice
*/
#include "detection_vision/utils2.h"
#include <glog/logging.h>
#include <fcntl.h>
#include <fstream>
#include <exception>

namespace detection
{
void ProtoHelpFun::ReadProtoFromTextFile(const std::string& filename, Message* proto)
{
  int fd = open(filename.c_str(), O_RDONLY);
  if (fd == -1)
  {
    std::string err = "read config file " + filename + " failed";
    LOG(ERROR) << err;
    close(fd);
    throw (err);
  }

  FileInputStream* input = new FileInputStream(fd);
  bool success = google::protobuf::TextFormat::Parse(input, proto);
  delete input;
  close(fd);
  if (!success)
  {
    std::string err = "parse text to inner object failed";
    LOG(ERROR) << err;
    throw err;
  }
}

void ProtoHelpFun::ReadProtoFromBinaryFile(const std::string& filename, Message* proto)
{
  int fd = open(filename.c_str(), O_RDONLY);
  if (fd == -1)
  {
    std::string err = "read config file " + filename + " failed";
    LOG(ERROR) << err;
    close(fd);
    throw err;
  }
  ZeroCopyInputStream* raw_input = new FileInputStream(fd);
  CodedInputStream* coded_input = new CodedInputStream(raw_input);
  coded_input->SetTotalBytesLimit(kProtoReadBytesLimit, kProtoReadBytesWarningThreshold);
  bool success = proto->ParseFromCodedStream(coded_input);
  delete coded_input;
  delete raw_input;
  close(fd);
  if (!success)
  {
    std::string err = "parse binary data to inner object failed";
    LOG(ERROR) << err;
    throw err;
  }
}
}